package com.fone.player.storage.download;

import java.util.ArrayList;
import java.util.HashMap;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import com.fone.player.entity.Download;
import com.fone.player.storage.StorageModule;
import com.fone.player.util.L;

/**
 * 
 * 应用下载管理
 * 
 * @author wangyang
 * @since 2014年6月13日
 */
public class DownloadAppManager {
	private static final String TAG = DownloadAppManager.class.getSimpleName();
	private HashMap<String, DownloadAppRunnable> mDownloadRunnableMap = new HashMap<String, DownloadAppRunnable>();
	private static final DownloadAppManager mInstance = new DownloadAppManager();

	public static DownloadAppManager getInstance() {
		return mInstance;
	}

	private DownloadAppManager() {
		NotificationHandle.getInstance();
	}

	/**
	 * 
	 * 获取当前正在下载的集合
	 * 
	 * @return ArrayList<DownloadRunnable> 当前正在下载的集合
	 */
	public ArrayList<DownloadAppRunnable> getDownloadRunnableList() {
		ArrayList<DownloadAppRunnable> downloadRunnableList = new ArrayList<DownloadAppRunnable>();
		downloadRunnableList.addAll(mDownloadRunnableMap.values());
		return downloadRunnableList;
	}

	/**
	 * 
	 * 下载任务
	 * 
	 * @param download
	 *            下载对象
	 * @return int 操作结果<br>
	 *         1 添加成功<br>
	 *         0 服务未启动<br>
	 *         -1 任务已存在 <br>
	 *         -2添加异常
	 */
	public int addDownloadFile(Download download) {

		// 判断任务是否重复
		if (mDownloadRunnableMap.containsKey(download.getDownloadUrl())) {

			DownloadAppRunnable downloadRunnable = mDownloadRunnableMap
					.get(download.getDownloadUrl());

			if (downloadRunnable != null) {

				if (downloadRunnable.isIsStop()) {

					// 删除已停止的任务
					mDownloadRunnableMap.remove(download.getDownloadUrl());

				} else {

					// 重复
					return -1;

				}
			}

		}

		// 创建下载任务,开始下载
		DownloadAppRunnable downloadRunnable = new DownloadAppRunnable(
				mHandler, download);
		ThreadPoolManager.getInstance().addFileTask(downloadRunnable);
		mDownloadRunnableMap.put(download.getDownloadUrl(), downloadRunnable);
		return 1;

	}

	/**
	 * 
	 * 更新下载任务
	 * 
	 * @param download
	 *            下载对象
	 * @return int 操作结果<br>
	 *         1 更新成功<br>
	 *         2创建任务成功
	 */
	public int updateDownloadFile(Download download) {

		L.v(TAG, "updateDownloadFile", "start");

		// 判断任务是否重复
		if (mDownloadRunnableMap.containsKey(download.getDownloadUrl())) {

			L.v(TAG, "updateDownloadFile", "get DownloadRunnable");
			DownloadAppRunnable downloadRunnable = mDownloadRunnableMap
					.get(download.getDownloadUrl());

			if (downloadRunnable != null) {

				if (downloadRunnable.isIsStop()) {

					L.v(TAG, "updateDownloadFile", "DownloadRunnable is stop");

					// 删除已停止的任务
					mDownloadRunnableMap.remove(download.getDownloadUrl());

				} else {

					L.v(TAG, "updateDownloadFile",
							"DownloadRunnable is repeat,set download");

					// 更新配置文件
					downloadRunnable.setDownload(download);

					mDownloadRunnableMap.put(download.getDownloadUrl(),
							downloadRunnable);
					return 1;

				}
			}
		}
		// 创建下载任务,开始下载
		DownloadAppRunnable downloadRunnable = new DownloadAppRunnable(
				mHandler, download);
		ThreadPoolManager.getInstance().addFileTask(downloadRunnable);
		mDownloadRunnableMap.put(download.getDownloadUrl(), downloadRunnable);
		L.v(TAG, "updateDownloadFile", "addFileTask");
		return 1;

	}

	/**
	 * 
	 * 开始任务
	 * 
	 * @param download
	 *            下载对象
	 * @return void
	 */
	public void startFile(Download download) {

	}

	/**
	 * 
	 * 暂停任务
	 * 
	 * @param download
	 *            下载对象
	 * @return void
	 */
	public void pauseFile(Download download) {

	}

	/**
	 * 
	 * 删除任务
	 * 
	 * @param download
	 *            下载对象
	 * @return void
	 */
	public void deleteFile(Download download) {

	}

	public static Handler mHandler = new Handler(Looper.getMainLooper()) {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			Bundle bundle = null;
			switch (msg.what) {
			case StorageModule.MSG_DOWNLOAD_PROGRESS:
				bundle = msg.getData();
				if (bundle != null) {
					Download download = bundle.getParcelable(Download.DOWNLOAD);
					if (download != null) {
						NotificationHandle.getInstance().showNotification(
								download);
					}

				}
				break;
			case StorageModule.MSG_DOWNLOAD_SUCCESS:
				bundle = msg.getData();
				if (bundle != null) {
					Download download = bundle.getParcelable(Download.DOWNLOAD);
					if (download != null) {
						NotificationHandle.getInstance().showNotification(
								download);
					}
				}
				break;
			case StorageModule.MSG_DOWNLOAD_ERROR:
				L.v(TAG, "handleMessage", "MSG_DOWNLOAD_ERROR");
				bundle = msg.getData();
				if (bundle != null) {
					Download download = bundle.getParcelable(Download.DOWNLOAD);
					if (download != null) {
						NotificationHandle.getInstance().showNotification(
								download);
					}
				}
				break;
			case StorageModule.MSG_CACHE_ERROR:
				if (CacheDownloadService.isNetwork()) {
					// FoneUtil.showToast(sContext, R.string.network_error);
					L.e(TAG, "handleMessage", "MSG_CACHE_ERROR isNet=false");
				}
				bundle = msg.getData();
				if (bundle != null) {
					String errorCode = bundle.getString("error_code");
					String errorMsg = bundle.getString("error_msg");
					L.e(TAG, "handleMessage", "MSG_CACHE_ERROR errorCode="
							+ errorCode + " errorMsg=" + errorMsg);
					// FoneUtil.showToast(sContext, "视频地址解析失败.errorCode="
					// + errorCode + " errorMsg=" + errorMsg);
				} else {
					L.e(TAG, "handleMessage", "MSG_CACHE_ERROR bundle=null");
					// FoneUtil.showToast(sContext, "视频地址解析失败.");
				}
				break;
			default:
				break;
			}
		}
	};
}
